package com.adou.common.util;

import java.io.*;

import com.github.junrar.exception.RarException;
import com.github.junrar.rarfile.FileHeader;
import org.apache.commons.io.IOUtils;

import com.github.junrar.Archive;

public class Junziprar {

    public static final String SEPARATOR = File.separator;

    /**
     * 解压指定RAR文件到指定的路径
     *
     * @param srcRarFile 需要解压RAR文件
     * @param destPath   指定解压路径
     */
    public static void unrar(File srcRarFile, String destPath) {
        if (!destPath.endsWith(SEPARATOR)) {
            destPath += SEPARATOR;
        }
        OutputStream unOut = null;
        try {
            Archive archive = new Archive(srcRarFile);
            FileHeader fileHeader = archive.nextFileHeader();
            while (null != fileHeader) {
                if (!fileHeader.isDirectory()) {
                    // 1 根据不同的操作系统拿到相应的 destDirName 和 destFileName
                    String destFileName,destDirName;
                    if (SEPARATOR.equals("/")) {        // 非windows系统
                        destFileName = (destPath + fileHeader.getFileNameString()).replaceAll("\\\\", "/");
                        destDirName = destFileName.substring(0, destFileName.lastIndexOf("/"));
                    } else {        // windows系统
                        destFileName = (destPath + fileHeader.getFileNameString()).replaceAll("/", "\\\\");
                        destDirName = destFileName.substring(0, destFileName.lastIndexOf("\\"));
                    }
                    // 2创建文件夹
                    File dir = new File(destDirName);
                    if (!dir.exists() || !dir.isDirectory()) {
                        dir.mkdirs();
                    }
                    // 抽取压缩文件
                    unOut = new FileOutputStream(new File(destFileName));
                    archive.extractFile(fileHeader, unOut);
                    unOut.flush();
                    unOut.close();
                }
                fileHeader = archive.nextFileHeader();
            }
            archive.close();
        } catch (RarException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(unOut);
        }
    }

    public static void main(String[] args) {
    }
}
